package com.jiqiu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jiqiu.entity.Admin;
import com.jiqiu.exception.LoginException;
import com.jiqiu.exception.RegisterException;
import com.jiqiu.mapper.AdminMapper;
import com.jiqiu.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiqiu.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author jiqiu
 * @since 2024-07-30
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    @Autowired
    private AdminMapper adminMapper;

    @Override
    public Admin login(String username, String password) {
        if(username.length() <5 || username.length() > 15){
            throw new LoginException("请输入5-15位的账户名");
        }
        if(password.length() <5 || password.length() > 15){
            throw new LoginException("请输入5-15位的密码");
        }
        String md5Password = Md5Util.getMD5String(password);
        LambdaQueryWrapper<Admin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 查询用户
        lambdaQueryWrapper.eq(Admin::getUsername, username);
        Admin admin = adminMapper.selectOne(lambdaQueryWrapper);
        if (admin == null) {
            throw new LoginException("用户不存在");
        }
        if (!admin.getPassword().equals(md5Password)) {
            throw new LoginException("输入密码错误");
        }
        return admin;
    }

    @Override
    public void register(String username, String password) {
        String md5Password = Md5Util.getMD5String(password);
        LambdaQueryWrapper<Admin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Admin::getUsername, username);
        List<Admin> admins = adminMapper.selectList(lambdaQueryWrapper);
        if (admins.size() > 1) {
            throw new RegisterException("已存在此账户，登录失败");
        }
        // 向数据库中添加该用户
        Admin admin = new Admin();
        admin.setUsername(username);
        admin.setPassword(md5Password);
        adminMapper.insert(admin);
    }
}
